﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ComicQ.Controller;
using ComicQ.Domain.Table;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for YearView.xaml
    /// </summary>
    public partial class YearView
    {
        private readonly YearController _yearControl;
        private IList<Year> _years;

        public YearView()
        {
            InitializeComponent();

            _yearControl = new YearController();
            _years = _yearControl.GetAllYear();
            dataGridYear.ItemsSource = _years;
        }

        private void RefreshGrid()
        {
            dataGridYear.ItemsSource = null;
            _years = _yearControl.GetAllYear();
            dataGridYear.ItemsSource = _years;
        }

        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var newWindow = new YearEditorView();

            if (newWindow.ShowDialog() != false)
            {
            }
            else
            {
                RefreshGrid();
            }
        }

        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridYear.SelectedItem == null)
                    throw new NullReferenceException();

                var year = _years
                        .Where(y => y.Id == _years[dataGridYear.SelectedIndex].Id)
                        .Select(y => y)
                        .Single();

                _yearControl.DeleteYear(year);
                MessageBox.Show("sukses menghapus year");
                RefreshGrid();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau didelete");
            }
        }

        private void ButtonEditClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridYear.SelectedItem == null)
                    throw new NullReferenceException();

                var newWindow = new YearEditorView(_years[dataGridYear.SelectedIndex]);

                if (newWindow.ShowDialog() != false)
                {
                }
                else
                {
                    RefreshGrid();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau diedit");
            }
        }
    }
}
